Pointers In CPP

Note:
General rule is "use reference in c++ over pointers, use pointers only if you have to". Pointers are avoided unless they are necessary.

Recap:

Have a look at Data modifiers to know more.

Example 1

#include <iostream>
#include <stdio.h>
int main(int argc, char *argv[])
{
	int a=5;
	int b=10;
	int c=a+b;
	int * d=&a;
	int * e=&b;
	std::cout<<"the values of a and b are "<<a<<"\t"<<b<<std::endl;
	std::cout<<"the address of a and b are "<<&a<<"\t"<<&b<<std::endl;
	std::cout<<"the address of a and b are "<<d<<"\t"<<e<<std::endl;
	std::cout<<"the value of a and b are "<<*&a<<"\t"<<*&b<<std::endl;
	std::cout<<"the value of a and b are "<<*d<<"\t"<<*e<<std::endl;
	
	return 0;
}

Output

the values of a and b are 5 10
the address of a and b are 0x7ff7b09ba3cc 0x7ff7b09ba3c8
the address of a and b are 0x7ff7b09ba3cc 0x7ff7b09ba3c8
the value of a and b are 5 10
the value of a and b are 5 10

Example 2

#include<iostream>
void fun(int *p)
{
*p=20;

}
int main()
{
int x=30;
int *y=&x; //here y is pointer variable which will store address of variable 'x'
fun(y);
std::cout<<x; //it will print 20 , since the value at address is changed in function, it can be useful.
return 0;

}